package cn.controller;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.kpi.entity.sys.UserEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.common.ConfigOption;
import cn.common.ExceResult;
import cn.common.ExcelHandler;
import cn.common.GridCommon;
import cn.common.LayTable;
import cn.filter.LoginCheck;
import cn.kpi.entity.attendance.AttSummaryEntity;
import cn.kpi.entity.sys.OrgEntity;
import cn.kpi.service.attendance.IAttFjGdService;
import cn.kpi.service.attendance.IAttTbService;
import cn.kpi.service.common.IOrgSummaryService;
import cn.kpi.service.sys.IOrgService;

@Controller
@RequestMapping("attfjgd")
public class AttFjGdController extends BaseController {

    @Autowired
    private IOrgService iOrgService;

    @Autowired
    private IAttTbService iAttTbService;

    @Autowired
    private IAttFjGdService iAttFjGdService;

    @Autowired
    private IOrgSummaryService iOrgSummaryService;

    @RequestMapping(value = "/att_fj_gd_list")
    public String AttFjGdList(Model model) {
        try {
            //List<OrgEntity> orglst = iOrgService.GetOrgList();
//			String where=this.GetLoginUserOrgidWhereForOrg();
//			List<OrgEntity> orglst = iOrgService.GetOrgListByWhere(where);
//			for (int i = 0; i < orglst.size(); i++) {
//				String html="";x
//				for(int j=0;j<orglst.get(i).getLevel();j++){
//					html+="&#12288;";
//				}
//				orglst.get(i).setOrgname(html+orglst.get(i).getOrgname());
//			}
//			model.addAttribute("orglst", orglst);


            UserEntity entity = this.GetLoginUser();
            if (entity.getRealname().contains("开发")) {
                model.addAttribute("isadmin", true);
            } else {
                model.addAttribute("isadmin", false);

            }
            Calendar cal = Calendar.getInstance();
            int year = cal.get(Calendar.YEAR);
            int month = cal.get(Calendar.MONTH) + 1;

            if(month ==1){
                year =year -1;
                month = 12;
            }
            else{
                month--;
            }
            model.addAttribute("year", year);
            model.addAttribute("month", month);
            //System.out.println(year+" "+month);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return "attendance/att_fj_gd_list";
    }

    @LoginCheck(description = true)
    @ResponseBody
    @RequestMapping(value = "/get_list")
    public LayTable<AttSummaryEntity> GetList(HttpServletRequest request) {

        List<AttSummaryEntity> lst = null;
        LayTable<AttSummaryEntity> layTable = new LayTable<AttSummaryEntity>();
        try {
            int page = Integer.parseInt(request.getParameter("page"));
            int limit = Integer.parseInt(request.getParameter("limit"));

            String year = request.getParameter("year");
            String mouth = request.getParameter("mouth");
            String orgid = request.getParameter("orgid");

            String orgsummaryid = request.getParameter("orgsummaryid");

            String realname = request.getParameter("realname");

            String where = "";
            if (year != null && year.length() > 0) {
                where += " AND year=" + year;
            }
            if (mouth != null && mouth.length() > 0) {
                where += " AND mouth=" + mouth;
            }
            if (orgid != null && orgid.length() > 0 && !orgid.equals("0")) {
                where += " AND szdw IN (" + orgid + ")";
            } else {
                where += " AND szdw IN (" + this.GetOrgListByRole() + ")";
            }

            if (orgsummaryid != null && orgsummaryid.length() > 0 && !orgsummaryid.equals("0")) {
                where += " AND orgsummaryid=" + orgsummaryid;
            }

            if (realname != null && realname.length() > 0) {
                where += " AND userid IN (SELECT userid FROM t_sys_user WHERE    cardno LIKE '%" + realname + "%'  or  realname LIKE '%" + realname + "%')";
            }

            int beginrow = (page - 1) * limit;
            int endrow = limit;


            String wherelimit = where + " LIMIT " + beginrow + "," + endrow;

            lst = iAttTbService.GetAttTbListByWhere(wherelimit);
            for (int i = 0; i < lst.size(); i++) {
                int rownum = beginrow + i + 1;
                lst.get(i).setRowNum(rownum);
            }

            int iCount = iAttTbService.GetAttTbListCountByWhere(where);
            layTable.setCode(0);
            layTable.setCount(iCount);
            layTable.setData(lst);

        } catch (Exception e) {
            layTable.setCode(500);
        }
        return layTable;
    }

    @ResponseBody
    @RequestMapping(value = "/attr_fjgd")
    public ExceResult AttFjGd(HttpServletRequest request, HttpServletResponse response) {
        ExceResult result = new ExceResult();
        result.setCode(400);
        result.setResult(0);
        try {
            Long orgid = Long.parseLong(request.getParameter("orgid"));
            Integer year = Integer.parseInt(request.getParameter("year"));
            Integer mouth = Integer.parseInt(request.getParameter("mouth"));

            OrgEntity orgentity = iOrgService.GetOrgById(orgid);

            String wheredsummary = " AND userid IN (SELECT userid FROM t_sys_user WHERE szdw IN (SELECT orgid FROM t_sys_org WHERE lft>=" + orgentity.getLft() + " AND lft<="
                    + orgentity.getRgt() + "))";


            String wheredetail = " AND attsummaryid IN( SELECT attsummaryid FROM t_user_att_summary WHERE userid IN (SELECT userid FROM t_sys_user WHERE szdw IN (SELECT orgid FROM t_sys_org WHERE lft>=" + orgentity.getLft() + " AND lft<="
                    + orgentity.getRgt() + ")))";

            int iResult = iAttFjGdService.UpdateAttFjGd(wheredsummary, wheredetail, this.GetLoginUserId());
            if (iResult > 0) {
                result.setCode(200);
                result.setResult(iResult);
                result.setMsg("操作成功");
            } else {
                result.setCode(300);
                result.setResult(iResult);
                result.setMsg("操作失败");
            }
        } catch (Exception ex) {
            result.setCode(500);
            result.setResult(0);
            result.setMsg("操作异常");
        }
        return result;
    }

    @ResponseBody
    @RequestMapping(value = "/export_excel")
    public ExceResult ExportExcel(HttpServletRequest request, HttpServletResponse response) {
        ExceResult result = new ExceResult();
        result.setCode(400);
        result.setResult(0);
        try {
            String year = request.getParameter("year");
            String mouth = request.getParameter("mouth");
            String orgid = request.getParameter("orgid");
            String orgsummaryid = request.getParameter("orgsummaryid");
            String where = "";
            if (year != null && year.length() > 0) {
                where += " AND year=" + year;
            }
            if (mouth != null && mouth.length() > 0) {
                where += " AND mouth=" + mouth;
            }
            if (orgid != null && orgid.length() > 0) {
                OrgEntity orgentity = iOrgService.GetOrgById(Long.parseLong(orgid));
                where += " AND szdw IN (SELECT orgid FROM t_sys_org WHERE lft>=" + orgentity.getLft() + " AND lft<="
                        + orgentity.getRgt() + ")";
            } else {
                where += " AND szdw (" + this.GetOrgListByRole() + ")";
            }

            if (orgsummaryid != null && orgsummaryid.length() > 0 && !orgsummaryid.equals("0")) {
                where += " AND orgsummaryid=" + orgsummaryid;
            }

            List<AttSummaryEntity> lst = iAttTbService.GetAttTbListByWhere(where);

            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");

            //String finalXlsxPath=ConfigOption.getInstance().getTemplateurl()+"/kqtemp.xlsx";
            //String filename=ConfigOption.getInstance().getTemplateurl()+"/考勤_"+sdf.format(new Date())+".xlsx";

            String finalXlsxPath = ConfigOption.getInstance().getTemplateurl() + "/kqtemp.xlsx";
            String filename = "kaoqin_" + sdf.format(new Date()) + ".xlsx";
            String titile = "房山公安分局"+lst.get(0).getOrgname()+" "+lst.get(0).getYear()+"年"+lst.get(0).getMouth()+"月考勤";
            Boolean olResult = ExcelHandler.writeExcelKq(lst, finalXlsxPath, filename, titile,response);

            if (olResult) {
                result.setCode(200);
                result.setResult(1);
                String urlen = ConfigOption.getInstance().getWeburl() + filename;
                result.setMsg(urlen);
            } else {
                result.setCode(300);
                result.setResult(0);
                result.setMsg("操作失败");
            }
        } catch (Exception ex) {
            result.setCode(500);
            result.setResult(0);
            result.setMsg("操作异常");
        }
        return result;
    }


    @ResponseBody
    @RequestMapping(value = "/export_excel_all")
    public ExceResult ExportExcelAll(HttpServletRequest request, HttpServletResponse response) {
        ExceResult result = new ExceResult();
        result.setCode(400);
        result.setResult(0);
        try {
            String year = request.getParameter("year");
            String mouth = request.getParameter("mouth");

            String where = "";
            if (year != null && year.length() > 0) {
                where += " AND year=" + year;
            }
            if (mouth != null && mouth.length() > 0) {
                where += " AND mouth=" + mouth;
            }


            List<AttSummaryEntity> lst = iAttTbService.GetAttTbListByWhereOrderBy(where);

            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");

            //String finalXlsxPath=ConfigOption.getInstance().getTemplateurl()+"/kqtemp.xlsx";
            //String filename=ConfigOption.getInstance().getTemplateurl()+"/考勤_"+sdf.format(new Date())+".xlsx";

            String finalXlsxPath = ConfigOption.getInstance().getTemplateurl() + "/kqtemp.xlsx";
            String filename = "kaoqin_" + sdf.format(new Date()) + ".xlsx";
            String titile = "房山公安分局"+lst.get(0).getYear()+"年"+lst.get(0).getMouth()+"月考勤";
            Boolean olResult = ExcelHandler.writeExcelKq(lst, finalXlsxPath, filename,titile, response);

            if (olResult) {
                result.setCode(200);
                result.setResult(1);
                String urlen = ConfigOption.getInstance().getWeburl() + filename;
                result.setMsg(urlen);
            } else {
                result.setCode(300);
                result.setResult(0);
                result.setMsg("操作失败");
            }
        } catch (Exception ex) {
            result.setCode(500);
            result.setResult(0);
            result.setMsg("操作异常");
        }
        return result;
    }

    @ResponseBody
    @RequestMapping(value = "/export_excel_sum_all")
    public ExceResult ExportExcelSumAll(HttpServletRequest request, HttpServletResponse response) {
        ExceResult result = new ExceResult();
        result.setCode(400);
        result.setResult(0);
        try {
            String year = request.getParameter("year");
            String mouth = request.getParameter("mouth");

            String where = "";
            if (year != null && year.length() > 0) {
                where += " AND year=" + year;
            }
            if (mouth != null && mouth.length() > 0) {
                where += " AND mouth=" + mouth;
            }


            List<AttSummaryEntity> lst = iAttTbService.GetAttTbListByWhereOrderBy(where);

            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");

            //String finalXlsxPath=ConfigOption.getInstance().getTemplateurl()+"/kqtemp.xlsx";
            //String filename=ConfigOption.getInstance().getTemplateurl()+"/考勤_"+sdf.format(new Date())+".xlsx";

            String finalXlsxPath = ConfigOption.getInstance().getTemplateurl() + "/kqsumtemp.xlsx";
            String filename = "kaoqinsum_" + sdf.format(new Date()) + ".xlsx";
            String titile = "房山公安分局"+lst.get(0).getYear()+"年"+lst.get(0).getMouth()+"月考勤";
            Boolean olResult = ExcelHandler.writeExcelKqSum(lst, finalXlsxPath, filename,titile, response);

            if (olResult) {
                result.setCode(200);
                result.setResult(1);
                String urlen = ConfigOption.getInstance().getWeburl() + filename;
                result.setMsg(urlen);
            } else {
                result.setCode(300);
                result.setResult(0);
                result.setMsg("操作失败");
            }
        } catch (Exception ex) {
            result.setCode(500);
            result.setResult(0);
            result.setMsg("操作异常");
        }
        return result;
    }

    @LoginCheck(description = true)
    @ResponseBody
    @RequestMapping(value = "/get_org_summary_list")
    public LayTable<Map> GetOrgSummaryList(HttpServletRequest request) {

        List<Map> lst = null;
        LayTable<Map> layTable = new LayTable<Map>();
        try {
            int year = Integer.parseInt(request.getParameter("year"));
            int month = Integer.parseInt(request.getParameter("month"));
            String strstatus = request.getParameter("status");
            String where = "";

            Calendar cal = Calendar.getInstance();
            int currentyear = cal.get(Calendar.YEAR);
            int currentmonth = cal.get(Calendar.MONTH) + 1;
            if (currentyear != year) {
                currentmonth = 12;
            }

            where += " AND orgid IN (" + this.GetOrgListByRole() + ")";
            lst = iOrgSummaryService.GetOrgSummaryList(where, year, month, strstatus, currentmonth);
            layTable.setCode(0);
            layTable.setCount(lst.size());
            layTable.setData(lst);

        } catch (Exception e) {
            e.printStackTrace();
            layTable.setCode(500);
        }
        return layTable;
    }


    @LoginCheck(description = true)
    @ResponseBody
    @RequestMapping(value = "/get_org_summary_list_grid")
    public GridCommon<Map> GetOrgSummaryListGrid(HttpServletRequest request) {

        List<Map> lst = null;
        GridCommon<Map> countlist = new GridCommon<Map>();
        try {
            int year = Integer.parseInt(request.getParameter("year"));
            int month = Integer.parseInt(request.getParameter("month"));
            String strorgid = request.getParameter("orgid");
            String strstatus = request.getParameter("status");
            String where = "";
            if (this.GetOrgListByRole() != "")
                where += " AND orgid IN (" + this.GetOrgListByRole() + ")";

            Calendar cal = Calendar.getInstance();
            int currentyear = cal.get(Calendar.YEAR);
            int currentmonth = cal.get(Calendar.MONTH) + 1;
            if (currentyear != year) {
                currentmonth = 12;
            }

            if (strorgid != null && strorgid.length() > 0) {
                OrgEntity orgentity = iOrgService.GetOrgById(Long.parseLong(strorgid));
                where += " AND orgid IN ( SELECT orgid FROM t_sys_org WHERE lft>=" + orgentity.getLft() + " AND lft<="
                        + orgentity.getRgt() + ")";
            }

            lst = iOrgSummaryService.GetOrgSummaryList(where, year, month, strstatus, currentmonth);
            countlist.setCurrentPage(1);
            countlist.setPageSize(10);
            countlist.setItems(lst);
            countlist.setStatus(0);
            countlist.setMsg("");
            countlist.setCountRecord(lst.size());

        } catch (Exception e) {
            e.printStackTrace();
            countlist.setCurrentPage(1);
            countlist.setPageSize(10);
            countlist.setItems(null);
            countlist.setStatus(1);
            countlist.setMsg("操作成功");
        }
        return countlist;
    }

    @ResponseBody
    @RequestMapping(value = "/update_attstatus")
    public ExceResult UpdateAttStatus(HttpServletRequest request, HttpServletResponse response) {
        ExceResult result = new ExceResult();
        result.setCode(400);
        result.setResult(0);
        try {
            String strorgsummaryid = request.getParameter("orgsummaryid");
            String strstatus = request.getParameter("status");

            Long orgsummaryid = Long.parseLong(strorgsummaryid);
            int status = Integer.parseInt(strstatus);

            int iResult = 0;
            iResult = iAttFjGdService.UpdateAttStatus(orgsummaryid, status);
            if (iResult > 0) {
                result.setCode(200);
                result.setResult(iResult);
                result.setMsg("操作成功");
            } else {
                result.setCode(300);
                result.setResult(iResult);
                result.setMsg("操作失败");
            }
        } catch (Exception ex) {
            result.setCode(500);
            result.setResult(0);
            result.setMsg("操作异常");
            ex.printStackTrace();
        }
        return result;
    }


    @ResponseBody
    @RequestMapping(value = "/update_attstatusbm")
    public ExceResult UpdateAttStatusBm(HttpServletRequest request, HttpServletResponse response) {
        ExceResult result = new ExceResult();
        result.setCode(400);
        result.setResult(0);
        try {
            String strorgsummaryids = request.getParameter("orgsummaryids");
            String strstatus = request.getParameter("status");


            int status = Integer.parseInt(strstatus);
            String orgsummaryids = "(" + strorgsummaryids.substring(0, strorgsummaryids.length() - 1) + ")";
            int iResult = 0;
            iResult = iAttFjGdService.UpdateAttStatusByBm(orgsummaryids, status);
            if (iResult > 0) {
                result.setCode(200);
                result.setResult(iResult);
                result.setMsg("操作成功");
            } else {
                result.setCode(300);
                result.setResult(iResult);
                result.setMsg("操作失败");
            }
        } catch (Exception ex) {
            result.setCode(500);
            result.setResult(0);
            result.setMsg("操作异常");
            ex.printStackTrace();
        }
        return result;
    }


}
